package com.bsdk.install.device.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bsdk.common.core.domain.AjaxResult;
import com.bsdk.common.utils.SpringContextUtil;
import com.bsdk.install.device.ICommDeviceService;
import com.bsdk.install.device.comm.CommDevice;
import com.bsdk.install.domain.Device;
import com.bsdk.install.domain.Gateway;
import com.bsdk.install.queue.PublicQueue;
import com.bsdk.install.service.IDeviceService;
import com.bsdk.install.service.IGatewayService;
import com.bsdk.produce.domain.DeviceProduce;
import com.bsdk.produce.service.IDeviceProduceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author sunjian0225@163.com
 * @version 1.0
 * @title CommDeviceService
 * @description
 * @create 2024/2/2 11:06
 */
@Service
public class CommDeviceService implements ICommDeviceService {
    @Autowired
    private IDeviceProduceService deviceProduceService;

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IGatewayService gatewayService;
    @Override
    public AjaxResult ping(String gwSn, String devSn) {

        AjaxResult device = this.getDeviceProduce(devSn,gwSn);

        if (device.isSuccess()) {

            CommDevice commDevice = (CommDevice) device.get("data");

            AjaxResult resultCommand = commDevice.commandPing();

            if (resultCommand.isSuccess()) {

                //发送命令
                AjaxResult resultSend = this.send((JSONObject) resultCommand.get("data"));

                if (resultSend == null) {

                    return AjaxResult.error("设备通讯失败");

                } else {
                    if (resultSend.isSuccess()) {
                        JSONObject jsData = commDevice.result((JSONObject) resultSend.get("data"));
//                        //逻辑处理
//                        log.info("逻辑处理中");
                        return AjaxResult.success(jsData);
                    } else {
                        return resultSend;
                    }
                }


            } else {
                return resultCommand;
            }

        } else {

            return device;
        }
    }


    //注册锁
    @Override
    public AjaxResult bindGateway(String gwSn, String devSn) {

        AjaxResult device = this.getDeviceProduce(devSn,gwSn);

        if (device.isSuccess()) {

            CommDevice commDevice = (CommDevice) device.get("data");

            //AjaxResult resultCommand = commDevice.commandBind();
            AjaxResult resultCommand = commDevice.commandBind(commDevice.getFmac());

            if (resultCommand.isSuccess()) {

                //发送命令
                AjaxResult resultSend = this.send((JSONObject) resultCommand.get("data"));

                if (resultSend == null) {

                    return AjaxResult.error("设备通讯失败");

                } else {
                    if (resultSend.isSuccess()) {
                        JSONObject jsData = commDevice.result((JSONObject) resultSend.get("data"));
                        if((Integer) jsData.get("code") == 200){
                            //生成安装信息
                            Gateway gateway = gatewayService.getOne(new LambdaQueryWrapper<Gateway>().eq(Gateway::getDevId,commDevice.getDevId()));
                            if(gateway == null){
                                //查询生产库
                                DeviceProduce deviceProduce = deviceProduceService.getOne(new LambdaQueryWrapper<DeviceProduce>().eq(DeviceProduce::getDevId,commDevice.getDevId()).eq(DeviceProduce::getGw,1));
                                Gateway gateway1 = new Gateway();
                                gateway1.setMac(deviceProduce.getMac());
                                gateway1.setDevId(deviceProduce.getDevId());
                                gateway1.setPid(deviceProduce.getPid());
                                gateway1.setSn(deviceProduce.getSn());
                                gatewayService.save(gateway1);
                                gateway = gateway1;

                            }

                            Device device1 = deviceService.getOne(new LambdaQueryWrapper<Device>().eq(Device::getMac,commDevice.getcMac()));
                            if(device1 == null){
                                //查询生产库
                                DeviceProduce deviceProduce = deviceProduceService.getOne(new LambdaQueryWrapper<DeviceProduce>().eq(DeviceProduce::getMac,commDevice.getcMac()).eq(DeviceProduce::getGw,0));
                                Device device2 = new Device();
                                device2.setMac(deviceProduce.getMac());
                                device2.setPid(deviceProduce.getPid());
                                device2.setSn(deviceProduce.getSn());
                                deviceService.save(device2);
                                device1 = device2;

                            }
                            device1.setGatewayId(gateway.getId());
                            device1.updateById();

                        }
                        return AjaxResult.success(jsData);
                    } else {
                        return resultSend;
                    }
                }


            } else {
                return resultCommand;
            }

        } else {

            return device;
        }

    }

    @Override
    public AjaxResult searchGateway(String gwSn, String devSn) {

        AjaxResult device = this.getDeviceProduce(devSn,gwSn);

        if (device.isSuccess()) {

            CommDevice commDevice = (CommDevice) device.get("data");

            AjaxResult resultCommand = commDevice.commandSearch();

            if (resultCommand.isSuccess()) {

                //发送命令
                AjaxResult resultSend = this.send((JSONObject) resultCommand.get("data"));

                if (resultSend == null) {

                    return AjaxResult.error("设备通讯失败");

                } else {
                    if (resultSend.isSuccess()) {

                        JSONObject jsData = commDevice.result((JSONObject) resultSend.get("data"));
                        if((Integer) jsData.get("code") == 200){
                            //生成安装信息
                            JSONObject data = (JSONObject) jsData.get("data");

                            return AjaxResult.success(data);
                        }else{
                            return resultSend;
                        }
                    } else {
                        return resultSend;
                    }
                }


            } else {
                return resultCommand;
            }

        } else {

            return device;
        }

    }

    @Override
    public AjaxResult reset(String devSn) {

        AjaxResult device = this.getDeviceIntall(devSn);

        if (device.isSuccess()) {

            CommDevice commDevice = (CommDevice) device.get("data");

            AjaxResult resultCommand = commDevice.commandReset();

            if (resultCommand.isSuccess()) {

                //发送命令
                AjaxResult resultSend = this.send((JSONObject) resultCommand.get("data"));

                if (resultSend == null) {

                    return AjaxResult.error("设备通讯失败");

                } else {
                    if (resultSend.isSuccess()) {
                        JSONObject jsData = commDevice.result((JSONObject) resultSend.get("data"));
//                        //逻辑处理
//                        log.info("逻辑处理中");
                        return AjaxResult.success(jsData);
                    } else {
                        return resultSend;
                    }
                }


            } else {
                return resultCommand;
            }

        } else {

            return device;
        }

    }
    private AjaxResult getDeviceIntall(String devSn) {
        Device device = deviceService.getOne(new LambdaQueryWrapper<Device>().eq(Device::getSn,devSn));

        if (device == null) {

            return AjaxResult.error("设备不存在");

        } else {
            if(device.getGatewayId() > 0){

                Gateway gw = gatewayService.getById(device.getGatewayId());

                if (device != null) {
                    CommDevice commDevice = new CommDevice(gw.getDevId(),device.getMac(),gw.getMac());
                    return AjaxResult.success(commDevice);

                } else {
                    return AjaxResult.error("网关不存在");
                }

            }else{

                return AjaxResult.error("设备未绑定网关");
            }

        }
    }

    private AjaxResult getDeviceProduce(String devSn, String gwSn) {
        DeviceProduce gw = deviceProduceService.getOne(new LambdaQueryWrapper<DeviceProduce>().eq(DeviceProduce::getSn,gwSn).eq(DeviceProduce::getGw,1));

        if (gw == null) {

            return AjaxResult.error("网关不存在");

        } else {

            DeviceProduce device = deviceProduceService.getOne(new LambdaQueryWrapper<DeviceProduce>().eq(DeviceProduce::getSn,devSn).eq(DeviceProduce::getGw,0));

            if (device != null) {
                CommDevice commDevice = new CommDevice(gw.getDevId(),device.getMac(),gw.getMac());
                return AjaxResult.success(commDevice);

            } else {
                return AjaxResult.error("设备不存在");
            }

        }
    }

    private AjaxResult send(JSONObject jsonObject) {

        SpringContextUtil.getBean(PublicQueue.class).setDown(jsonObject);

        if (PublicQueue.MAPRESULTQUEUE.containsKey(jsonObject.getString("uId"))) {

            JSONObject jsonObject1 = null;
            try {
                jsonObject1 = (JSONObject) PublicQueue.MAPRESULTQUEUE.get(jsonObject.getString("uId")).poll(10, TimeUnit.SECONDS);


            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return AjaxResult.success(jsonObject1);

        } else {
            return AjaxResult.error("结果队列不存在");
        }

    }
}
